package com.syezon.wifikey.cengwang;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.syezon.android.base.utils.ToastUtils;
import com.syezon.wifikey.R;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.download.DownloadHelper;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.web.WebHelper;
import com.syezon.wifikey.wxapi.WxShare;

import butterknife.BindView;
import butterknife.OnClick;

public class CengwangTipDetailActivity extends BaseActivity {


    private static WebHelper.WebLoadCallBack webLoadCallBack;
    @BindView(R.id.rl_top)
    RelativeLayout mRlTop;
    @BindView(R.id.img_back)
    ImageView mImgBack;
    @BindView(R.id.tv_web_title)
    TextView mTvTitle;
    @BindView(R.id.pb_web)
    ProgressBar mPbWeb;
    @BindView(R.id.webView)
    WebView mWebView;
    @BindView(R.id.fl_web)
    FrameLayout mFlWeb;
    private String mUrl;

    @BindView(R.id.rl_share)
    RelativeLayout mRlShare;


    /**
     * 设置页面加载回调
     */
    public static void setWebLoadCallBack(WebHelper.WebLoadCallBack callBack) {
        webLoadCallBack = callBack;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        mUrl = extras.getString(WebHelper.ARG_URL, "");
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_cengwang_activity_web;
    }


    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        StatusBarUtil.setPaddingSmart(this, mRlTop);
        initWebView();
        mRlShare.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(mUrl)) {
            mWebView.loadUrl(mUrl);
        } else {
            ToastUtils.showShort(" 链接异常！");
        }
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    if (url.startsWith("http") || url.startsWith("https")) { //http和https协议开头的执行正常的流程
                        return super.shouldOverrideUrlLoading(view, url);
                    } else {  //其他的URL则会开启一个Acitity然后去调用原生APP
                        Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        if (in.resolveActivity(getPackageManager()) == null) {
                            //说明系统中不存在这个activity
                        } else {
                            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                            startActivity(in);
                            //如果想要加载成功跳转可以 这样
                        }
                        return true;
                    }
                } catch (Exception e) {

                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                view.loadUrl("file:///android_asset/error.html");
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            private boolean isSendLoadUrlOk = false;

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress < 100) {
                    if (mPbWeb.getVisibility() != View.VISIBLE) {
                        mPbWeb.setVisibility(View.VISIBLE);
                    }
                    mPbWeb.setProgress(newProgress);
                } else {
                    mPbWeb.setVisibility(View.GONE);
                }
                if ((newProgress > 80 || newProgress == 100) && !isSendLoadUrlOk) {
                    if (webLoadCallBack != null) {
                        webLoadCallBack.loadComplete(mUrl);
                    }
                    isSendLoadUrlOk = true;
                    mRlShare.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTvTitle.setText(title);
            }
        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                DownloadHelper.downloadUrl(url);
            }
        });
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= 21) {
            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSetting.setBlockNetworkImage(false);
    }

    @OnClick({R.id.img_back, R.id.rl_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rl_share:
                WxShare.wxSceneSession("http://res.hodanet.com/upload/sy/20200411/16/1589186458920.html", "网络被蹭不要怕，防蹭网攻略看这里！", "赶紧来看看吧~", "cengwangtipshare");
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mWebView.removeAllViews();
            mWebView.destroy();
            mFlWeb.removeAllViews();
        } catch (Exception e) {
        }
    }

    @Override
    public void finish() {
        webLoadCallBack = null;
        super.finish();
    }
}
